package com.saifan.wyy_ov.ui.onlishop;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;

import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SearchView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.data.bean.CommonDataBean;
import com.saifan.wyy_ov.data.bean.StoreBean;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.IGetData;
import com.saifan.wyy_ov.model.interfaces.ResponseData;
import com.saifan.wyy_ov.ui.view.BaseActivity;
import com.saifan.wyy_ov.utils.CommonAdapter;
import com.saifan.wyy_ov.utils.SoftUtil;
import com.saifan.wyy_ov.utils.StringUtil;
import com.saifan.wyy_ov.utils.ToastUtil;
import com.saifan.wyy_ov.utils.ViewHolderHelper;

/**
 * @author WangLi
 * @date 2015年3月16日 下午7:56:27
 * @Description 搜索结果按钮
 * @version V1.0
 */

public class SearchActivity extends BaseActivity implements SearchView.OnQueryTextListener {
	private ListView listView;
	private RelativeLayout loadingLayout;
	private View loadmoreView;
	private List<StoreBean> list;
	private LinearLayout loadmoreLayout, loadmoreloading;
	private TextView loadfail;
	private IGetData getData;
	private int page = 0;
	private CommonDataBean requestBean;
	private String storeName = "";
	private boolean noDataFlag = false;
	private CommonAdapter<StoreBean> adapter;
	private boolean searchFlag = false;
	private boolean footerFlag = false;
	private SearchView searchView;
	private Toolbar toolbar;
	private String storeType;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);
		 storeType=getIntent().getStringExtra("storeType");
		storeName = getIntent().getStringExtra("name");
		requestBean = new CommonDataBean();
		requestBean.setYXDID(getRoomInfoBean().getXMBS());
		getData = new GetData();
		findViews();
		getDataInit();
	}

	@SuppressLint("InflateParams")
	private void findViews() {
		loadmoreView = getLayoutInflater().inflate(R.layout.listview_load_more, null);
		loadmoreLayout = (LinearLayout) loadmoreView.findViewById(R.id.loadmore_layout);
		loadingLayout = (RelativeLayout) findViewById(R.id.loading_lay);
		loadfail = (TextView) loadmoreView.findViewById(R.id.load_more_fail);
		toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
		setSupportActionBar(toolbar);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);

		listView = (ListView) findViewById(R.id.listview);
		list = new ArrayList<StoreBean>();
		adapter = new CommonAdapter<StoreBean>(SearchActivity.this, list, R.layout.store_item) {

			@Override
			public void convert(ViewHolderHelper helper, StoreBean item) {
				helper.setText(R.id.store_name, StringUtil.returnShow(item.getStoreName()));
				ImageView statePic = helper.getView(R.id.state_pic);
				if (item.isIsDelivery()) {
					statePic.setVisibility(View.VISIBLE);
				} else {
					statePic.setVisibility(View.GONE);
				}
				String date = "", time = "";
				if (!StringUtil.isNullOrEmpty(item.getBusinessDate())) {
					date = item.getBusinessDate().replace(",", "至");
				}
				if (!StringUtil.isNullOrEmpty(item.getBusinessTime())) {
					time = item.getBusinessTime().replace(",", "至");
				}
				helper.setText(R.id.store_time, date + " " + time);
				if (StringUtil.isNullOrEmpty(item.getDeliveryInstructions())) {
					helper.setText(R.id.note, StringUtil.returnShow(String.valueOf(item.getDeliveryAmount())) + " 元起送");
				} else {
					helper.setText(
							R.id.note,
							StringUtil.returnShow(String.valueOf(item.getDeliveryAmount())) + " 元起送/"
									+ StringUtil.returnShow(item.getDeliveryInstructions()));
				}
				helper.setImageByUrl(R.id.store_img, item.getHeadPhoto());
			}
		};
		listView.setAdapter(adapter);
		// 添加listview滚动监听,滚动到底部自动加载数据
		listView.setOnScrollListener(new OnScrollListener() {
			// AbsListView rootview 这个view对象就是listview
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
					if (view.getLastVisiblePosition() == view.getCount() - 1) {
						if (!noDataFlag) {
							page++;
							getDataInit();
						}
					}
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				// int lastItem = firstVisibleItem + visibleItemCount - 1;
			}
		});
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				Intent intent = new Intent(SearchActivity.this, StoreDetailsActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("data", list.get(arg2));
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});
	}

	@SuppressLint("NewApi")
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.around_store, menu);
		// 对搜索监听
		searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
		searchView.setOnQueryTextListener(this);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onQueryTextChange(String arg0) {
		return false;
	}

	@Override
	public boolean onQueryTextSubmit(String arg0) {
		storeName = arg0;
		searchFlag = true;
		page = 0;
		SoftUtil.hideSoftInput(SearchActivity.this, searchView);
		getDataInit();
		return true;
	}

	private void getDataInit() {
		if (searchFlag) {
			list.clear();
			loadingLayout.setVisibility(View.VISIBLE);
			searchFlag = false;
		}
		requestBean.setPage(page);
		requestBean.setStoreName(storeName);
		requestBean.setStoreType(storeType);
		getData.getDataJson(SearchActivity.this, Api.StoreList.STORELIST, requestBean, "", new ResponseData() {

			@Override
			public void onSuccess(String json) {
				loadingLayout.setVisibility(View.GONE);
				List<StoreBean> data = (new Gson()).fromJson(json, new TypeToken<List<StoreBean>>() {}.getType());
				if (data.size() > 0) {
					if (page == 0) {
						list = data;
						adapter.mDatas = list;
					} else {
						list.addAll(data);
					}
					if (page == 0) {
						if (data.size() >= 10) {
							if (footerFlag == false) {
								listView.addFooterView(loadmoreView);
								loadmoreLayout.setOnClickListener(new View.OnClickListener() {
									@Override
									public void onClick(View v) {
										if (loadfail.getVisibility() == View.VISIBLE) {
											loadmoreloading.setVisibility(View.VISIBLE);
											loadfail.setVisibility(View.GONE);
											getDataInit();
										}
									}
								});
								footerFlag = true;
								noDataFlag = false;
							}
						} else {
							noDataFlag = true;
						}
					} else {
						noDataFlag = true;
						if (data.size() < 10) {
							if (footerFlag) {
								listView.removeFooterView(loadmoreView);
							}
						}
					}
					adapter.notifyDataSetChanged();
				} else {
					if (page == 0) {
						ToastUtil.showToast(SearchActivity.this, "暂无店铺信息");
					} else {
						page--;
						noDataFlag = true;
						ToastUtil.showToast(SearchActivity.this, "暂无更多店铺信息");
					}
				}
			}

			@Override
			public void onFailed(String str) {
				loadingLayout.setVisibility(View.GONE);
				if (page != 0) {
					if (footerFlag) {
						loadmoreloading.setVisibility(View.GONE);
						loadfail.setVisibility(View.VISIBLE);
					}
				}
			}
		});
	}
}
